import './graphPanel.css'

import { Tabs, Drawer, Popover, Spin } from 'antd'
import { useState, useEffect } from 'react'
import DisputeThumbnail from './DisputeThumbnail'
import { selectedDisputeThumbnailAtom } from '@/app/atoms'
import { useAtom } from 'jotai'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import GraphDrawerContent from './GraphDrawerContent'
import dynamic from 'next/dynamic'
import { useSearchParams } from 'next/navigation'
import { useQuery } from '@tanstack/react-query'
import { apiClient } from '@/lib/apiClient'
import { useParams } from 'next/navigation'
import { arrayHelper } from '@/utils/common'

const GraphContent = dynamic(() => (import('./GraphContent')), { ssr: false })

function TipContent () {
    return (
        <div className='text-xs text-gray-400'>
            <p>
                1.单击节点进行查看详情；
            </p>
            <p>
                2.双击节点进行图谱探索；
            </p>
            <p>
                3.已展开的节点再次双击进行收回；
            </p>
            <p>
                4.对于人员实体右击头像跳转纠纷人员画像。
            </p>
        </div>
    )
}

function GraphOperationTip () {
    return (
        <Popover title="操作提示" content={<TipContent />}>
            <div>
                <ExclamationCircleOutlined style={{ fontSize: 14 }}/>
                <span className='text-sm pl-2'>
                    操作提示
                </span>
            </div>
        </Popover>
    )
}

function People2thingDisputeThumbnailContainer ({
    selectedAssociationMethod,
    selectedLitigant,
    selectedResource,
    selectedCode,
    selectedType,
    selectedId,
    selectedOccurrenceTime,
}) {
    const params = useParams()

    const { error, data, status } = useQuery({
        queryKey: [
            'graph_people2thing',
            selectedAssociationMethod,
            selectedLitigant,
            selectedResource,
            selectedCode,
            selectedType,
            selectedId,
            selectedOccurrenceTime,
        ],
        queryFn: async () => {
            const data = await apiClient.post(
                `graphAnalysis/affairs/pc`,
                {
                    json: {
                        idCard: params?.id,
                        associationTypes: selectedAssociationMethod,
                        disputePersonNames: selectedLitigant,
                        disputeSource: selectedResource,
                        disputeId: selectedCode,
                        disputePersonIdCard: selectedId,
                        disputeType: selectedType,
                        disputeOccurrenceTime: selectedOccurrenceTime,
                    }
                },
            ).json()

            return data
        },
        select: (result) => {
            if (result.code === 200) {
                return arrayHelper(result.data).map((item) => {
                    if (item?.disputeSource === '110警情') {
                        return {
                            tag: 'police_case',
                            id: item?.disputeId,
                            date: item?.alarmTime,
                            title: item?.disputeType,
                            content: item?.alarmContent,
                            nodeType: 'dispute'
                        }
                    }

                    if (item?.disputeSource === '协同办案') {
                        return {
                            tag: 'joint_investigation',
                            id: item?.disputeId,
                            date: item?.alarmTime,
                            title: item?.disputeType,
                            content: item?.briefCaseDescription,
                            nodeType: 'dispute'
                        }
                    }
                })
                .filter((item) => { return item !== undefined })
            }
            return []
        }
    })

    if (status === 'pending') {
        return (
            <div className='h-[70%] grid place-content-center'>
                <Spin size="large"/>
            </div>
        )
    }

    if (status === 'error') {
        return (
            <DisputeThumbnail list={[]} type="1"/>
        )
    }


    if (status === 'success') {
        return (
            <DisputeThumbnail list={data} type="1"/>
        )
    }
}

function People2PeopleDisputeThumbnailContainer ({
    selectedAssociationMethod,
    selectedLitigant,
    selectedResource,
    selectedCode,
    selectedType,
    selectedId,
    selectedOccurrenceTime,
}) {
    const params = useParams()

    const { error, data, status } = useQuery({
        queryKey: [
            'graph_people2people',
            selectedAssociationMethod,
            selectedLitigant,
            selectedResource,
            selectedCode,
            selectedType,
            selectedId,
            selectedOccurrenceTime,
        ],
        queryFn: async () => {
            const data = await apiClient.post(
                `graphAnalysis/affairs/pp`,
                {
                    json: {
                        idCard: params?.id,
                        associationTypes: selectedAssociationMethod,
                        disputePersonNames: selectedLitigant,
                        disputeSource: selectedResource,
                        disputeId: selectedCode,
                        disputePersonIdCard: selectedId,
                        disputeType: selectedType,
                        disputeOccurrenceTime: selectedOccurrenceTime,
                    }
                },
            ).json()

            return data
        },
        select: (result) => {
            if (result.code === 200) {
                return arrayHelper(result.data).map((item) => {
                    return {
                        id: item?.disputePeople?.idCard,
                        name: item?.disputePeople?.name,
                        relationList: item?.relationList,
                        content: arrayHelper(item?.disputeInfoList).map((item) => {
                            return {
                                tag: (((disputeSource) => {
                                    if (disputeSource === '110警情') {
                                        return 'police_case'
                                    }

                                    if (disputeSource === '协同办案') {
                                        return 'joint_investigation'
                                    }

                                    return ''
                                })(item?.disputeSource)),
                                id: item?.disputeId,
                                date: item?.alarmTime,
                                title: item?.disputeType,
                                content: (((disputeSource) => {
                                    if (disputeSource === '110警情') {
                                        return item?.alarmContent
                                    }

                                    if (disputeSource === '协同办案') {
                                        return item?.briefCaseDescription
                                    }

                                    return ''
                                })(item?.disputeSource)),
                            }
                        }),
                        nodeType: 'people',
                    }
                })
                .filter((item) => { return item !== undefined })
            }
            return []
        }
    })

    if (status === 'pending') {
        return (
            <div className='h-[70%] grid place-content-center'>
                <Spin size="large"/>
            </div>
        )
    }

    if (status === 'error') {
        return (
            <DisputeThumbnail list={[]} type="2"/>
        )
    }


    if (status === 'success') {
        return (
            <DisputeThumbnail list={data} type="2"/>
        )
    }
}

export default function GraphPanel ({
    selectedAssociationMethod,
    selectedLitigant,
    selectedResource,
    selectedCode,
    selectedType,
    selectedId,
    selectedOccurrenceTime,
}) {

    const searchParams = useSearchParams()
    const [key, setKey] = useState(() => ('1'))
    const [selectedDisputeThumbnail, setSelectedDisputeThumbnail] = useAtom(selectedDisputeThumbnailAtom)
    const [isContentLoading, setIsContentLoading] = useState(() => (false))

    const handleIsLoading = (isLoading) => {
        setIsContentLoading(() => (isLoading))
    }

    let open = false

    if (selectedDisputeThumbnail?.id) {
        open = true
    }

    if (typeof selectedDisputeThumbnail === 'undefined') {
        open = false
    }

    const handleSelectGraph = (key) => {
        setKey(() => (key))
        setSelectedDisputeThumbnail(() => (undefined))
    }

    useEffect(() => {
        const graph = searchParams.get('graph')

        if (graph === 'people2thing') {
            setKey(() => ('1'))
        }

        if (graph === 'people2people') {
            setKey(() => ('2'))
        }

        if (graph === 'all') {
            setKey(() => ('3'))
        }
    }, [searchParams])

    return (
        <div 
            className='my-2 px-4 pb-2 bg-white rounded-md'
            style={{ height: 'calc(100% - 120px)', position: 'relative' }}
        >
            <Tabs
                id='graph-panel-id'
                activeKey={key}
                items={[
                    {
                        key: '1',
                        label: '人事图谱',
                        children: '',
                    },
                    {
                        key: '2',
                        label: '人人图谱',
                        children: '',
                    },
                    {
                        key: '3',
                        label: '综合图谱',
                        children: '',
                    },
                ]}
                tabBarExtraContent={{
                    right: <GraphOperationTip />
                }}
                onChange={handleSelectGraph}
            />
            <div
                className="flex"
                style={{ height: 'calc(100% - 40px)' }}
            >
                <div 
                    style={{ flexBasis: '362px' }}
                    className='border-r border-gray-100 py-3 overflow-y-auto dispute_thumbnail_content_container'
                >
                    {key === '1' || key === '3'
                        ? (
                            <People2thingDisputeThumbnailContainer
                                selectedAssociationMethod={selectedAssociationMethod}
                                selectedLitigant={selectedLitigant}
                                selectedResource={selectedResource}
                                selectedCode={selectedCode}
                                selectedType={selectedType}
                                selectedId={selectedId}
                                selectedOccurrenceTime={selectedOccurrenceTime}
                            />
                        )
                        : null
                    }
                    {key === '2'
                        ? (
                            <People2PeopleDisputeThumbnailContainer
                                selectedAssociationMethod={selectedAssociationMethod}
                                selectedLitigant={selectedLitigant}
                                selectedResource={selectedResource}
                                selectedCode={selectedCode}
                                selectedType={selectedType}
                                selectedId={selectedId}
                                selectedOccurrenceTime={selectedOccurrenceTime}
                            />
                        )
                        : null
                    }
                </div>
                <div style={{ flex: 1 }}>
                    <Spin
                        spinning={isContentLoading}
                        size='large' 
                        style={{ width: '100%', height: '100%', marginBottom: '20px', paddingTop: '15%' }}
                    />
                    <GraphContent
                        selectedAssociationMethod={selectedAssociationMethod}
                        selectedLitigant={selectedLitigant}
                        selectedResource={selectedResource}
                        selectedCode={selectedCode}
                        selectedType={selectedType}
                        selectedId={selectedId}
                        selectedOccurrenceTime={selectedOccurrenceTime}
                        selectedGraphType={key}
                        handleIsLoading={handleIsLoading}
                    />
                </div>
            </div>
            <Drawer
                id='graph-drawer'
                placement="right"
                closable={false}
                open={open}
                getContainer={false}
                mask={false}
                autoFocus={false}
                style={{ borderRadius: '6px' }}
            >
                <GraphDrawerContent type={key}/>
            </Drawer>
        </div>
    )
}